package com.umeox.watch.moto.dataservice.mqtt.rpc;

import android.annotation.SuppressLint;
import android.content.Intent;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.umeox.moto.common.log.Logger;
import com.umeox.watch.moto.apiclient.model.MessageDTO;
import com.umeox.watch.moto.dataservice.base.BaseApp;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.dataservice.mqtt.Topic;
import com.umeox.watch.moto.dataservice.mqtt.impl.MqttServiceDelegate;
import com.umeox.watch.moto.dataservice.services.ApiService;

import java.util.List;

/**
 * Created by Rambo 2021/9/29
 * Describe: 处理云消息推送并回复消息已经收到
 */
public class PushMsgRpc {

    protected String responseTopic;
    protected JSONObject msgJsonObj;

    private PushMsgRpc(Builder builder) {
        this.responseTopic = Topic.CLOUD_PUSH_REPLY_TOPIC_PREFIX + getResponseCode(builder.topic);
        this.msgJsonObj = builder.msgJsonObj;
    }

    private String getResponseCode(String topic) {
        int index = topic.lastIndexOf("/");
        return topic.substring(index + 1);
    }


    @SuppressLint("WrongConstant")
    public void handleOrResponse() {
        if (msgJsonObj != null) {
            int cnt = msgJsonObj.getInteger("cnt");//消息条数
            JSONArray msgJsonArr = msgJsonObj.getJSONArray("payload");
            JSONObject ack = msgJsonObj.getJSONObject("ack");
            List<MessageDTO> msgList = null;
            try{
                msgList = JSONArray.parseArray(msgJsonArr.toJSONString(), MessageDTO.class);
            }catch (Exception exception){
                exception.printStackTrace();
            }finally {
                //回复云端消息已经收到
                MqttServiceDelegate.ackPushMsg(responseTopic, ack);
                //处理消息
                byte[] chatMsgListByteArray = ApiService.getChatMessage(msgList);
                Logger.i("PushMsgRpc", "Send Broadcast[" + Constants.ACTION_NEW_CHAT_MESSAGE + "]");
                Intent intent = new Intent(Constants.ACTION_NEW_CHAT_MESSAGE);
                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                intent.putExtra(Constants.EXTRA_CHAT_MSG, chatMsgListByteArray);
                BaseApp.getInstance().sendBroadcast(intent);
            }
        }

    }


    public static class Builder {
        private String topic;
        private JSONObject msgJsonObj;

        public Builder topic(String topic) {
            this.topic = topic;
            return this;
        }

        public Builder params(JSONObject msgJsonObj) {
            this.msgJsonObj = msgJsonObj;
            return this;
        }


        public PushMsgRpc build() {
            return new PushMsgRpc(this);
        }

    }
}
